#pragma once
#include <pthread.h>
#include <queue>
#define SIZE 5
using namespace std;
template <class T=int>
class BlockQueue
{
private:
    bool IsFull()
    {
        return _capacity == _q.size();
    }
    bool IsEmpty()
    {
        return _q.empty();
    }

public:
    BlockQueue(int capacity = SIZE) : _capacity(capacity)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_customercond, nullptr);
        pthread_cond_init(&_productorcond, nullptr);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_customercond);
        pthread_cond_destroy(&_productorcond);
    }

    void push(T &x)
    {
        pthread_mutex_lock(&_mutex);
        while(IsFull())
        {
            pthread_cond_wait(&_productorcond, &_mutex);
        }
        _q.push(x);
        pthread_mutex_unlock(&_mutex);
        // 唤醒消费者
        pthread_cond_signal(&_customercond);
    }

    void pop(T *out)
    {
        pthread_mutex_lock(&_mutex);
        while(IsEmpty())
        {
            pthread_cond_wait(&_customercond, &_mutex);
        }
        *out = _q.front();
        _q.pop();
        pthread_mutex_unlock(&_mutex);
        // 唤醒生产者
        pthread_cond_signal(&_productorcond);
    }

private:
    queue<T> _q;
    pthread_mutex_t _mutex;
    pthread_cond_t _customercond;
    pthread_cond_t _productorcond;
    int _capacity;
};
